package com.zhanghu.backendZray.manager.role;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhanghu.backendZray.cache.ContextCache;
import com.zhanghu.backendZray.cache.UserMenuCache;
import com.zhanghu.backendZray.constants.CommonConstant;
import com.zhanghu.backendZray.converter.UserConverter;
import com.zhanghu.backendZray.exception.ApiException;
import com.zhanghu.backendZray.pojo.dto.*;
import com.zhanghu.backendZray.pojo.entity.*;
import com.zhanghu.backendZray.pojo.request.LoginRequest;
import com.zhanghu.backendZray.pojo.request.roleMenu.RoleMenuRequest;
import com.zhanghu.backendZray.pojo.request.user.UserPageRequest;
import com.zhanghu.backendZray.pojo.request.userRole.UserRoleRequest;
import com.zhanghu.backendZray.pojo.vo.MenuVo;
import com.zhanghu.backendZray.pojo.vo.UserVo;
import com.zhanghu.backendZray.service.*;
import com.zhanghu.backendZray.utils.Md5Util;
import com.zhanghu.backendZray.utils.token.TokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.zhanghu.backendZray.constants.CommonConstant.*;

/**
 * @author ZhangDong
 * @date 2024/8/3 10:43
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class UserRoleMenuManager {
    private final UserService userService;
    private final UserRoleService userRoleService;
    private final RoleService roleService;
    private final MenuService menuService;
    private final RoleMenuService roleMenuService;
    private final UserConverter userConverter;
    private final UserOnlineTokenService userOnlineTokenService;
    private final TrialRecordService trialRecordService;
    private final PendingTaskService pendingTaskService;

    /**
     * 手机号密码登录
     */
    @Transactional(rollbackFor = Exception.class)
    public LoginResDTO doNormalLogin(LoginRequest loginRequest) {
        String phone = loginRequest.getPhone();
        String password = loginRequest.getPassword();
        User user = userService.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getPhone, phone));
        Optional.ofNullable(user).orElseThrow(() -> new ApiException("手机号不存在！"));
        String calPassword = Md5Util.get2Md5(password);
        Assert.isTrue(user.getPassword().equals(calPassword), "密码不正确");
//        String token = JwtUtil.createToken(new UserTokenInfo(user));
        String loginToken = TokenUtil.createLoginToken();
        userOnlineTokenService.saveOrUpdate(user, loginToken);
        removeTrialRoleByJudgeTrialRecord(user.getId());
        return new LoginResDTO(loginToken, currentUserMenu(user.getId()));
    }

    /**
     * 微信登录并返回token
     * 这种方式是跳转到新的微信授权页的方式
     */
    /*@Transactional(rollbackFor = Exception.class)
    public LoginResDTO doWxLogin(AuthUser authUser, String wxLoginKey) {
        AuthToken token = authUser.getToken();
        String openId = token.getOpenId();
        User user = userService.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getWxOpenId, openId));
        if (user == null) {
            log.info("wx login, no this openId:{}", openId);
            user = new User();
            user.setWxOpenId(openId);
            user.setWxExpireIn(token.getExpireIn());
            user.setWxNickName(authUser.getNickname());
            user.setWxAccessToken(token.getAccessToken());
            user.setWxRefreshToken(token.getRefreshToken());
            user.setWxAvatar(authUser.getAvatar());
            user.setName(authUser.getNickname());
            userService.save(user);
            // 给游客角色
            addGuestRole(user.getId());
        } else {
            user.setWxExpireIn(token.getExpireIn());
            user.setWxNickName(authUser.getNickname());
            user.setWxAccessToken(token.getAccessToken());
            user.setWxRefreshToken(token.getRefreshToken());
            user.setWxAvatar(authUser.getAvatar());
            userService.updateById(user);
        }
        String zToken = JwtUtil.createToken(new UserTokenInfo(user));
        return new LoginResDTO(zToken, currentUserMenu(user.getId()));
    }*/

    /**
     * 微信登录并返回token
     * 这种方式是网页里内嵌的方式
     */
    @Transactional(rollbackFor = Exception.class)
    public LoginResDTO doWxLoginInner(String responseBody) {
        WxLoginDTO wxLoginDTO = JSON.parseObject(responseBody, WxLoginDTO.class);
        wxLoginDTO.getAccess_token();
        String openId = wxLoginDTO.getOpenid();
        String accessToken = wxLoginDTO.getAccess_token();
        String refreshToken = wxLoginDTO.getRefresh_token();
        String expiresIn = wxLoginDTO.getExpires_in();

        User user = userService.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getWxOpenId, openId));
        if (user == null) {
            log.info("wx login, no this openId:{}", openId);
            // 获取用户个人信息
            String userInfoUrl = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s", accessToken, openId);
            String userInfoRes = HttpRequest.get(userInfoUrl).execute().body();
            WxUserInfoDTO wxUserInfoDTO = JSON.parseObject(userInfoRes, WxUserInfoDTO.class);

            user = new User();
            user.setWxOpenId(openId);
            user.setWxExpireIn(Integer.valueOf(expiresIn));
            user.setWxNickName(wxUserInfoDTO.getNickname());
            user.setWxAccessToken(accessToken);
            user.setWxRefreshToken(refreshToken);
            user.setWxAvatar(wxUserInfoDTO.getHeadimgurl());
            user.setName("");
            userService.save(user);
            // 给游客角色
            addGuestRole(user.getId());
        } else {
            user.setWxExpireIn(Integer.valueOf(expiresIn));
            user.setWxAccessToken(accessToken);
            user.setWxRefreshToken(refreshToken);
            userService.updateById(user);
        }
//        String zToken = JwtUtil.createToken(new UserTokenInfo(user));
        String loginToken = TokenUtil.createLoginToken();
        userOnlineTokenService.saveOrUpdate(user, loginToken);
        return new LoginResDTO(loginToken, currentUserMenu(user.getId()));
    }

    /**
     * 用户表分页查询
     */
    public Page<UserVo> page(UserPageRequest request) {
        Page<User> pageQuery = new Page<>(request.getPageNum(), request.getPageSize());
        Page<User> page = userService.page(pageQuery, Wrappers.lambdaQuery(new User())
                .like(StrUtil.isNotEmpty(request.getName()), User::getName, request.getName())
                .like(StrUtil.isNotEmpty(request.getPhone()), User::getPhone, request.getPhone())
        );
        List<User> list = page.getRecords();
        List<UserVo> userVos = userConverter.entity2Vos(list);
        Page<UserVo> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());

        if (CollUtil.isNotEmpty(list)) {
            // 在线状态
            List<UserOnlineToken> onlineTokens = userOnlineTokenService.listByUserIdIn(userVos.stream()
                    .map(UserVo::getId).collect(Collectors.toList()));
            Map<Integer, UserOnlineToken> onlineTokenMap = onlineTokens.stream().collect(Collectors
                    .toMap(UserOnlineToken::getUserId, Function.identity()));
            for (UserVo userVo : userVos) {
                Integer id = userVo.getId();
                UserOnlineToken userOnlineToken = onlineTokenMap.get(id);
                if (userOnlineToken == null) {
                    continue;
                }
                userVo.setTokenExpireTime(userOnlineToken.getTokenExpireTime());
                userVo.setOnlineStatus(userOnlineToken.getOnlineStatus());
            }
        }
        resultPage.setRecords(userVos);
        return resultPage;
    }


    /**
     * 获取当前用户菜单列表
     *
     * @param userId
     * @return
     */
    public List<String> currentUserMenu(Integer userId) {
        List<String> menuEnNameList = menuService.getMenusByUserId(userId).stream().map(MenuDTO::getEnName).collect(Collectors.toList());
        boolean superAdmin = isSuperAdmin(userId);
        if (superAdmin) {
            menuEnNameList.add(CommonConstant.SUPER_ADMIN_ROLE);
        }
        return menuEnNameList;
    }

    /**
     * 获取用户的角色列表
     *
     * @param userId
     * @return
     */
    public List<String> userRoleList(Integer userId) {
        List<Integer> roleIdList = userRoleService.getRoleIdListByUserId(userId);
        return roleIdList.stream().map(roleService::getById).map(Role::getEnName).collect(Collectors.toList());
    }

    /**
     * 游客试用三天
     * 1. 判断是否只是游客身份 + 没有试用记录
     * 2. 新增试用角色 + 新增试用记录
     * 3. 过试用期，删除试用角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void guestTrial() {
        Integer userId = ContextCache.currentUserId();
        boolean noTrialRecord = removeTrialRoleByJudgeTrialRecord(userId);
        boolean onlyGuestRole = onlyGuestRole(userId);
        // 不仅仅是游客身份
        if (!onlyGuestRole) {
            return;
        }
        // 有试用记录，只给一次试用机会
        if (!noTrialRecord) {
            return;
        }
        // 新增试用记录
        TrialRecord newTrialRecord = new TrialRecord();
        newTrialRecord.setUserId(userId);
        newTrialRecord.setBeginTime(LocalDateTime.now());
        newTrialRecord.setEndTime(LocalDateTime.now().plusDays(3));
        trialRecordService.save(newTrialRecord);
        // 新增试用角色
        addTrialRole(ContextCache.currentUserId());
        // 新增一条待办提醒，这里其实就是右下角的提示框
        pendingTaskService.addTrialPendingTask(userId);
        // 事务执行成功后，刷新用户菜单缓存
        userMenuFlushAfterTransactionFinish(userId);
    }

    private void userMenuFlushAfterTransactionFinish(Integer userId) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                try {
                    userMenuFlush(userId);
                } catch (Exception e) {
                    log.error("游客试用三天, 刷新用户菜单缓存, userId:{}, error:{}", userId, e);
                }
            }
        });
    }

    /**
     * 通过判断试用记录来决定是否删除试用角色
     *
     * @param userId
     * @return true: 无试用记录; false: 有试用记录
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean removeTrialRoleByJudgeTrialRecord(Integer userId) {
        TrialRecord trialRecord = trialRecordService.getOne(new LambdaQueryWrapper<>(TrialRecord.class).eq(TrialRecord::getUserId, userId));
        if (trialRecord == null) {
            return true;
        }
        LocalDateTime endTime = trialRecord.getEndTime();
        // 没到试用截止日期
        if (endTime.isAfter(LocalDateTime.now())) {
            return false;
        }
        // 删除用户的试用角色
        removeTrialRole(userId);
        return false;
    }

    /**
     * 判断是否超级管理员
     *
     * @param userId
     * @return
     */
    public boolean isSuperAdmin(Integer userId) {
        List<Integer> roleIdList = userRoleService.getRoleIdListByUserId(userId);
        if (CollUtil.isEmpty(roleIdList)) {
            return false;
        }
        Role role = roleService.getOne(new LambdaQueryWrapper<>(Role.class)
                .in(Role::getId, roleIdList)
                .eq(Role::getEnName, CommonConstant.SUPER_ADMIN_ROLE));
        return role != null;
    }

    /**
     * 为用户新增游客身份
     */
    @Transactional(rollbackFor = Exception.class)
    public void addGuestRole(Integer userId) {
        Integer guestRoleId = roleService.getGuestRoleId();
        if (guestRoleId == null) {
            return;
        }
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(guestRoleId);
        userRoleService.save(userRole);
    }

    /**
     * 为用户新增试用角色身份
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTrialRole(Integer userId) {
        Integer guestRoleId = roleService.getTrialRoleId();
        if (guestRoleId == null) {
            return;
        }
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(guestRoleId);
        userRoleService.save(userRole);
    }

    /**
     * 删除用户的试用角色身份
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeTrialRole(Integer userId) {
        Integer guestRoleId = roleService.getTrialRoleId();
        if (guestRoleId == null) {
            return;
        }
        userRoleService.remove(new LambdaQueryWrapper<>(UserRole.class).eq(UserRole::getUserId, userId).eq(UserRole::getRoleId, guestRoleId));
    }

    /**
     * 为用户新增会员身份
     */
    @Transactional(rollbackFor = Exception.class)
    public void addMemberRole(Integer userId) {
        Integer guestRoleId = roleService.getMemberRoleId();
        if (guestRoleId == null) {
            return;
        }
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(guestRoleId);
        userRoleService.save(userRole);
    }

    /**
     * 为用户新增家庭组身份
     */
    @Transactional(rollbackFor = Exception.class)
    public void addFamilyRole(Integer userId) {
        Integer guestRoleId = roleService.getFamilyRoleId();
        if (guestRoleId == null) {
            return;
        }
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(guestRoleId);
        userRoleService.save(userRole);
        // 刷新用户菜单权限
        userMenuFlush(userId);

    }

    /**
     * 获取全量菜单，并设置选中状态
     */
    public List<MenuVo> getMenuListByRoleId(Integer roleId) {
        List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
        List<Integer> menuIdList = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<MenuVo> allMenuVoList = menuService.listAll();
        allMenuVoList.forEach(menuVo -> menuVo.setSelected(menuIdList.contains(menuVo.getId())));
        return allMenuVoList;
    }

    /**
     * 只获取被选中子菜单的id集合 vue el-tree这边需要获取所有子节点id，不需要父节点。
     */
    public List<Integer> getSelectedMenuListByRoleId(Integer roleId) {
        List<RoleMenu> roleMenus = roleMenuService.list(
                new LambdaQueryWrapper<RoleMenu>()
                        .eq(RoleMenu::getRoleId, roleId));
        List<Integer> menuIdList = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        if (CollUtil.isEmpty(menuIdList)) {
            return Collections.emptyList();
        }
        List<Menu> list = menuService.list(new LambdaQueryWrapper<Menu>().in(Menu::getId, menuIdList).eq(Menu::getLeaf, true));
        return list.stream().map(Menu::getId).collect(Collectors.toList());
    }

    /**
     * 为角色设置菜单
     */
    @Transactional(rollbackFor = Exception.class)
    public void roleMenuSetting(RoleMenuRequest roleMenuRequest) {
        Integer roleId = roleMenuRequest.getRoleId();
        boolean existsRole = roleService.exists(new LambdaQueryWrapper<Role>().eq(Role::getId, roleId));
        if (!existsRole) {
            throw new ApiException(ApiResponse.Status.SERVICE_FAILED, "角色不存在");
        }
        List<Integer> menuIdList = roleMenuRequest.getMenuIdList() == null ?
                Collections.emptyList() : roleMenuRequest.getMenuIdList();
        if (CollUtil.isNotEmpty(menuIdList)) {
            boolean existsMenu = menuService.exists(new LambdaQueryWrapper<Menu>().in(Menu::getId, menuIdList));
            if (!existsMenu) {
                throw new ApiException(ApiResponse.Status.SERVICE_FAILED, "菜单不存在");
            }
            // 获取子菜单id及其父菜单id
            menuIdList = menuService.listAllMenuIdBYChildIdList(menuIdList);
        }
        List<Integer> menuIdResultList = menuIdList;
        List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
        List<Integer> oldMenuIdList = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<Integer> addMenuIdList = menuIdList.stream().filter(menuId -> !oldMenuIdList.contains(menuId)).collect(Collectors.toList());
        List<Integer> deleteMenuIdList = oldMenuIdList.stream().filter(menuId -> !menuIdResultList.contains(menuId)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(addMenuIdList)) {
            List<RoleMenu> addRoleMenus = addMenuIdList.stream().map(menuId -> {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                return roleMenu;
            }).collect(Collectors.toList());
            roleMenuService.saveBatch(addRoleMenus);
        }
        List<Integer> deleteRoleMenuIdList = roleMenus.stream().filter(roleMenu -> deleteMenuIdList.contains(roleMenu.getMenuId()))
                .map(RoleMenu::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(deleteRoleMenuIdList)) {
            roleMenuService.removeBatchByIds(deleteRoleMenuIdList);
        }
        // 用户菜单缓存变更
        // 哪些用户有此角色
        List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, roleId));
        if (CollUtil.isEmpty(userRoleList)) {
            return;
        }
        List<Integer> affectUserIdList = userRoleList.stream().map(UserRole::getUserId).distinct().collect(Collectors.toList());
        userMenuFlush(affectUserIdList);
    }

    /**
     * 批量刷新用户菜单缓存
     *
     * @param userIdList
     */
    public void userMenuFlush(List<Integer> userIdList) {
        if (CollUtil.isEmpty(userIdList)) {
            return;
        }
        for (Integer currentUserId : userIdList) {
            userMenuFlush(currentUserId);
        }
    }

    /**
     * 用户菜单变更，刷新缓存
     *
     * @param userId
     */
    private void userMenuFlush(Integer userId) {
        List<String> menuEnNameList = currentUserMenu(userId);
        UserMenuCache.putMenu(userId, menuEnNameList);
    }

    /**
     * 获取当前权限下所有人员，超管能查所有
     */
    public List<UserVo> listAll() {
        UserTokenInfo userTokenInfo = ContextCache.currentUser();
        Integer id = userTokenInfo.getId();
        boolean superAdmin = isSuperAdmin(id);
        List<User> list = superAdmin ? userService.list(new LambdaQueryWrapper<User>().notIn(User::getName, "")) :
                userService.list(new LambdaQueryWrapper<User>().eq(User::getId, id));
        return userConverter.entity2Vos(list);
    }

    /**
     * 用户退出登录
     */
    public void logout() {
        userOnlineTokenService.logout();
    }

    /**
     * 用户下线
     */
    public void offline(int id) {
        userOnlineTokenService.offline(id);
    }

    /**
     * 为用户配置角色
     *
     * @param userRoleRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void userRoleSetting(UserRoleRequest userRoleRequest) {
        Integer userId = userRoleRequest.getUserId();
        userRoleService.remove(new LambdaQueryWrapper<>(UserRole.class)
                .eq(UserRole::getUserId, userId));
        List<Integer> roleIdList = userRoleRequest.getRoleIdList();
        List<UserRole> list = roleIdList.stream().map(r -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userRoleRequest.getUserId());
            userRole.setRoleId(r);
            return userRole;
        }).collect(Collectors.toList());
        userRoleService.saveBatch(list);
        // 用户菜单缓存刷新
        userMenuFlush(userId);
    }

    /**
     * 超管删除角色
     *
     * @param roleId
     */
    public void deleteRole(Long roleId) {
        // 删除前获取之前都有哪些用户拥有此角色
        List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, roleId));
        if (CollUtil.isNotEmpty(userRoleList)) {
            List<Integer> userIdList = userRoleList.stream().map(UserRole::getUserId).distinct().collect(Collectors.toList());
            List<User> users = userService.listByIds(userIdList);
            String collect = users.stream().map(User::getName).collect(Collectors.joining("、"));
            throw new ApiException("此角色仍有人员：《" + collect + "》与之关联，请先移除关联关系, 再删除！");
        }
        roleService.removeById(roleId);
    }

    /**
     * 超管删除菜单
     *
     * @param menuId
     */
    public void deleteMenu(Integer menuId) {
        Menu menu = menuService.getById(menuId);
        Optional.ofNullable(menu).orElseThrow(() -> new ApiException("此菜单不存在"));
        List<Menu> childList = menuService.list(Wrappers.<Menu>lambdaQuery().eq(Menu::getParentId, menuId));
        if (CollUtil.isNotEmpty(childList)) {
            throw new ApiException("此菜单下存在子菜单，请先删除子菜单");
        }
        // 如果有角色还在使用此菜单，提示先移除与此角色的关联
        List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId, menuId));
        if (CollUtil.isNotEmpty(roleMenus)) {
            List<Integer> roleIdList = roleMenus.stream().map(RoleMenu::getRoleId).distinct().collect(Collectors.toList());
            List<Role> roles = roleService.listByIds(roleIdList);
            String collect = roles.stream().map(Role::getName).collect(Collectors.joining("、"));
            throw new ApiException("此菜单仍有角色：《" + collect + "》与之关联，请先移除关联关系, 再删除！");
        }
        menuService.removeById(menuId);
    }

    /**
     * 用户是否只是游客角色
     *
     * @param userId
     * @return
     */
    public boolean onlyGuestRole(Integer userId) {
        Integer guestRoleId = roleService.getGuestRoleId();
        if (guestRoleId == null) {
            throw new ApiException("系统未创建游客角色，请联系系统管理员！");
        }
        List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId).eq(UserRole::getRoleId, guestRoleId));
        if (CollUtil.isEmpty(userRoleList)) {
            return false;
        }
        return userRoleList.size() == 1;
    }

    /**
     * 试用角色文件上传限制
     *
     * @param userId
     * @return true：限制，false：不限制
     */
    public void trialRoleFileUploadLimit(Integer userId) {
        List<String> roleList = userRoleList(userId);
        // 包含其中任何一个角色
        boolean canPass = roleList.stream().anyMatch(r -> r.equals(MEMBER_ROLE) || r.equals(SUPER_ADMIN_ROLE) || r.equals(ADMIN_ROLE) || r.equals(SUPER_ADMIN_FAMILY_ROLE));
        if (canPass) {
            return;
        }
        if (!roleList.contains(TRIAL_ROLE)) {
            new ApiException("您的试用时间已过，购买会员即可永久使用此功能！");
        }
        TrialRecord trialRecord = trialRecordService.getOne(new LambdaQueryWrapper<>(TrialRecord.class).eq(TrialRecord::getUserId, userId));
        if (trialRecord.getEndTime().isBefore(LocalDateTime.now())) {
            throw new ApiException("您的试用时间已过，购买会员即可永久使用此功能！");
        }
        Integer fileUploadCount = trialRecord.getFileUploadCount();
        if (fileUploadCount >= TRIAL_FILE_UPLOAD_LIMIT) {
            throw new ApiException("文件上传的试用次数已达上限，购买会员即可永久使用此功能");
        }
    }
}
